package com.itheima.agent.controller;

import com.itheima.agent.repository.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.content.Media;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Objects;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class ChatController {

    private final ChatClient chatClient;

    private final ChatHistoryRepository chatHistoryRepository;

    @RequestMapping(value = "/chat", produces = "text/html;charset=UTF-8")
    public Flux<String> chat(@RequestParam(value = "prompt", defaultValue = "讲个笑话") String prompt,
                             @RequestParam("chatId") String chatId,
                             @RequestParam(value = "files", required = false) List<MultipartFile> files
    ) {
//        1.保存会话id
        chatHistoryRepository.save("chat", chatId);
//        2.请求模型
        if (files == null || files.isEmpty()) {
//            没有附件,纯文本聊天
            return textChat(prompt, chatId);
        } else {
//            有附件,多模态聊天
            return multiModalChat(prompt, chatId, files);
        }
    }

    /**
     * 有附件,多模态聊天
     *
     * @param prompt
     * @param chatId
     * @param files
     * @return
     */
    private Flux<String> multiModalChat(String prompt, String chatId, List<MultipartFile> files) {
//        1.解析多媒体
        List<Media> media = files.stream()
                .map(
                        file -> new Media(MediaType.valueOf(Objects.requireNonNull(file.getContentType())),
                                file.getResource()))
                .toList();
//        2.请求模型
        return chatClient
                .prompt() // 传入user提示词
                .user(p -> p.text(prompt).media(media.toArray(Media[]::new)))
                .advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                .stream() // 同步请求,将ai的答案流式返回
                .content(); // 返回相应结果
    }

    /**
     * 没有附件,纯文本聊天
     *
     * @param prompt
     * @param chatId
     * @return
     */
    private Flux<String> textChat(String prompt, String chatId) {
        return chatClient
                .prompt(prompt) // 传入user提示词
                .advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                .stream() // 同步请求,将ai的答案流式返回
                .content(); // 返回相应结果
    }
}
